﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;
using DotNetNuke.Common.Utilities;

using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework.Providers;
using Satrabel.HttpModules.Provider;
using DotNetNuke.Modules.dnnsimplearticle.Components;
//using DotNetNuke.Modules.dnnsimplearticle.services;



namespace Satrabel.OpenUrlRewriter.DNNSimpleArticle
{
    public class DNNSimpleArticleUrlRuleProvider : UrlRuleProvider
    {

        private const string ProviderType = "urlRule";
        private const string ProviderName = "dnnSimpleArticleUrlRuleProvider";

        private readonly ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(ProviderType);
        private readonly bool includePageName = true;

        public DNNSimpleArticleUrlRuleProvider() {
            var objProvider = (DotNetNuke.Framework.Providers.Provider)_providerConfiguration.Providers[ProviderName];
            if (!String.IsNullOrEmpty(objProvider.Attributes["includePageName"]))
            {
                includePageName = bool.Parse(objProvider.Attributes["includePageName"]);
            }
            //CacheKeys = new string[] { "DNNSimpleArticle-ProperyValues-All" };
        }

        public override List<UrlRule> GetRules(int PortalId)
        {
            List<UrlRule> Rules = new List<UrlRule>();

            ModuleController mc = new ModuleController();
            ArrayList modules = mc.GetModulesByDefinition(PortalId, "dnnsimplearticle");
            //foreach (ModuleInfo module in modules.OfType<ModuleInfo>().GroupBy(m => m.ModuleID).Select(g => g.First())){                
            foreach (ModuleInfo module in modules.OfType<ModuleInfo>())
            {
                var articles = ArticleController.GetArticles(module.ModuleID);
                
                
                foreach (var article in articles)
                {
                    var rule = new UrlRule
                    {
                        CultureCode = module.CultureCode,
                        TabId = module.TabID,
                        RuleType = UrlRuleType.Module,
                        Parameters = "aid="+article.ArticleId.ToString(),
                        Action = UrlRuleAction.Rewrite,
                        Url = CleanupUrl(article.Title),
                        RemoveTab = !includePageName
                    };                    
                    Rules.Add(rule);                    
                }
            }
             
            return Rules;
        }

    }
}